<template>
  <view class="card tn-padding-sm tn-margin-sm">
    <tanhuajiluPdf style="position: absolute;top: -999999px" ref="PDF" :jsonData="jsonData"
                   @upload="imgUpload"></tanhuajiluPdf>

    <inputForm v-model="form" ref="form" :list="list"
               @thr1Change="e=>form.thr1 = e"
               @thr2Change="e=>form.thr2 = e"
               @thr3Change="e=>form.thr3 = e"
               @thr4Change="e=>form.thr4 = e">
      <template #questionsList>
        <view v-for="(item, index) of form.questionsList" :key="index">
          <!--第1条不显示。
           第5条，根据第4条回答显示，是（不显示） 不是（显示）-->
          <template v-if="index > 0 && !(index ===4 && !form.questionsList[index-1].answer.includes('不是') )">
            <view :class="'border bd_'+index">
              <view class="tn-flex" style="margin-top: 20px;">
                <view>问：</view>
                <tn-input border type="textarea" autoHeight v-model="item.question"/>
              </view>
              <view class="tn-flex" style="margin-top: 10px;">
                <view>答：</view>
                <tn-input border type="textarea" v-model="item.answer"/>
              </view>
              <view class="tn-flex tn-flex-direction-row-reverse tn-margin-sm">
                <tn-button v-if="(index>10&&enquireIndex===0)||(index>1&&enquireIndex>0)" class="tn-flex-col-bottom" style="margin-left: 10px;"
                           @click="deleteItem(index)"
                           backgroundColor="tn-bg-red" fontColor="tn-color-white">删除
                </tn-button>
                <tn-button v-if="index+1 === form.questionsList.length" @click="addItem" backgroundColor="tn-bg-blue"
                           fontColor="tn-color-white">添加
                </tn-button>
              </view>
            </view>
          </template>
        </view>
      </template>
    </inputForm>
    <view class="tn-flex tn-flex-row-center tn-padding-xl">
      <tn-button v-if="$route.query.isClosed === '0'" @click="submit" backgroundColor="tn-bg-blue" style="width: 80%"
                 fontColor="tn-color-white">保存
      </tn-button>
    </view>

    <tn-modal v-model="erweima" :custom="true">
      <view class="custom-modal-content tn-flex tn-flex-direction-column tn-flex-col-center">
        <p style="margin-bottom: 8px;">谈话记录</p>
        <canvas id="qrcode" canvas-id="qrcode" style="width: 200px; height: 200px;"></canvas>
        <tn-button @click="downloadPDFFn('谈话记录')" backgroundColor="tn-bg-blue" style="width: 80%;margin-top: 16px;"
                   fontColor="tn-color-white">
          下载
        </tn-button>
      </view>
    </tn-modal>
  </view>
</template>

<script>
import InputForm from "../../../components/inputForm.vue";
import {
  addEnquire, addSign,
  getDocPhoto,
  getEnQuestionDetail,
  getEnquireDetail, getRoadAndHeadByDepartId,
  getSign,
  saveCatlog, updateSign,
  uploadLp
} from "@/api/lupeiwenshu";
import tanhuajiluPdf from "@/pages/roadCompensation/tanhuajilu/tanhuajiluPdf.vue";
import wenshuPdf from "@/pages/roadCompensation/wenshubeizhu/wenshuPdf.vue";
import fujianmixins from "../js/fujianmixins";
import {toast} from "@/utils/common";

export default {
  components: {wenshuPdf, InputForm, tanhuajiluPdf},
  mixins: [fujianmixins],
  data() {
    return {
      pdfData: {},
      signList: [],

      enquireIndex: 0,
      form: {
        // 被谈话人
        enquire: '',

        "id": "",
        "questionIds": "",
        orderNo: 0,
        questionsList: [],
        "remark": "",
        "documentId": '',
        btr: "",
        thr1: '',
        thr2: '',
        thr3: '',
        thr4: '',
      },
      list: [
        {
          label: "被谈话人：",
          prop: "enquire",
          type: 'select',
          props: {
            value: 'id',
            label: 'name'
          },
          dicData: [],
          fn: (item) => {
            this.enquireIndex = this.list.find(item => item.label === '被谈话人：').dicData.findIndex(item => item.id === this.form.enquire);
            this.init()
            this.form.questionsList = []
            let arr = this.list.filter(item => item.label === '被谈话人签名及时间：')
            arr.forEach(item => {
              item.hidden = true
            })
            arr[this.enquireIndex].hidden = false;
          }
        },
        {
          label: "案号：",
          prop: "questionIds",
          labelWidth: 120,
        },
        {
          label: "",
          prop: "questionsList",
          type: "slot",
        },
        {
          label: "备注：",
          prop: "remark",
        },
        {
          label: "被谈话人签名及时间：",
          prop: "btr",
          type: "signBoard",
          hidden: false,
          fn: (item) => {
            this.form.btr = item;
          },
        },
        {
          label: "被谈话人签名及时间：",
          prop: "btr2",
          type: "signBoard",
          hidden: true,
          fn: (item) => {
            this.form.btr2 = item;
          },
        },
        {
          label: "被谈话人签名及时间：",
          prop: "btr3",
          type: "signBoard",
          hidden: true,
          fn: (item) => {
            this.form.btr3 = item;
          },
        },
        {
          label: "被谈话人签名及时间：",
          prop: "btr4",
          type: "signBoard",
          hidden: true,
          fn: (item) => {
            this.form.btr4 = item;
          },
        },
        {
          label: "1谈话人签名及时间：",
          prop: "thr1",
          type: "signBoard",
        },
        {
          label: "2谈话人签名及时间：",
          prop: "thr2",
          type: "signBoard",
        },
        {
          label: "3谈话人签名及时间：",
          prop: "thr3",
          type: "signBoard",
        },
        {
          label: "4谈话人签名及时间：",
          prop: "thr4",
          type: "signBoard",
        },

      ]
    };
  },

  methods: {
    init() {
      this.getBase()

      // this.getDocPhoto()

      this.getSign()
    },
    getBase() {
      getEnquireDetail({
        documentId: this.$route.query.id
      }).then(res => {
        const doc = res.data.doc;
        // 被谈话人options
        this.list.find(item => item.label === '被谈话人：').dicData = doc.enquireList;
        this.form.enquire = doc.enquireList[this.enquireIndex].id;

        const driver = (doc.carProvince == null ? "/" : doc.carProvince) + (doc.carNo == null ? "" : doc.carNo);
        this.form = {
          ...this.form,
          id: doc?.enquireList?.length ? doc.enquireList[0].id : '',
          questionIds: doc?.caseInfo,
          documentId: doc.id,
          orderNo: 0,
        }
        this.getDetails(doc.enquireList[this.enquireIndex].id, {...doc,driver,fact:res.data.fact})
        this.$nextTick(() => {
          this.jsonData = {...res.data, ...this.form}
        })
      })
    },
    getDetails(id,doc) {
      getEnQuestionDetail({
        emquireId: id,
      }).then(res => {
        let {
          conAddr,
          companyName,
          job,
          telephone,
          idcardNum,
          gender,
          age,
          questionsList,
          id,
          remark,
          documentId,
          orderNo,
          askLocation,
          startTime,
          endTime,
          name,
          relation,
          ...form
        } = res.data;

        // 谈话内容格式化
        // 没有填写
        if(!questionsList.length){
          questionsList = [
            {
              question: "",
              answer: "",
            }, {
              question: "我们" + doc.factTwo + doc.driver + doc.carType + doc.recoNote.caseReason + "，造成路产损失，现对有关情况向你进行调查。你知道吗？",
              answer: "知道。",
            }, {
              question: "你的姓名、年龄、工作单位及职业？",
              // 后端返回年龄数据有问题（""会返0）
              answer: "我叫" + doc.enquireList[0].name + "，" + (doc.enquireList[0].age === 0 ? "" : doc.enquireList[0].age) + "岁，" + doc.enquireList[0].companyName + doc.enquireList[0].job + "。",
            }, {
              question: "你是车辆的所有权人吗？",
              answer: "是。",
            }, {
              question: "车辆所有权人是谁？",
              answer: "",
            }, {
              question: "请你叙述事故发生的经过？",
              answer: doc.fact,
            }, {
              question: "我们需要对损坏现场进行勘验，来确定具体的路产损失数量，勘验结果将作为你赔偿公路路产损失的事实依据。请你配合到场。",
              answer: "知道。",
            }, {
              question: "你对我们的调查享有陈述和申辩的权利，你知道吗？",
              answer: "知道。",
            }, {
              question: "请看谈话记录与你的陈述是否一致？",
              answer: "一致。",
            }, {
              question: "请看谈话记录的内容是否属实？",
              answer: "属实。",
            }, {
              question: "请签字摁手印。",
              answer: "好的。",
            }]
          if (this.enquireIndex > 0) {
            questionsList = [
              {
                question: "",
                answer: "",
              },
              {
                question: "你是否申请回避？",
                answer: "不回避。",
              }]
          }
        }else{
          if (this.enquireIndex > 0){
            questionsList = [
                {
              question: "",
              answer: "",
            }
            ,...questionsList]
          }
        }

        // 备注
        if(!remark)remark = '/'

        this.form = {
          ...this.form,
          questionsList, id, remark, documentId, orderNo,
        };
        this.$nextTick(() => {
          this.jsonData = {
            ...this.jsonData,
            ...this.form, enquireIndex: this.enquireIndex,
            askLocation,
            startTime, endTime,
            name, relation,
            gender, age, idcardNum, telephone,
            companyName, job, conAddr
          }
        })
      })
    },
    submit() {

      let {btr,btr2, btr3, btr4, thr1, thr2, thr3, thr4, ...data} = this.form
      data.questionsList = data.questionsList.filter(item => item.question&&item.answer)
      if (this.form?.id) {
        addEnquire(data).then(res => {
          if (res.code === 200) {

            if (this.signList.length) {
              updateSign({
                doc_photo_id: this.$route.query.id,
                type_num: 1,
                interlocutor1: btr,
                interlocutor2: btr2,
                interlocutor3: btr3,
                interlocutor4: btr4,
                speaker1: thr1,
                speaker2: thr2,
                speaker3: thr3,
                speaker4: thr4,
              }).then(res => {
                console.log('res', res)

              })
            } else {
              addSign({
                doc_photo_id: this.$route.query.id,
                type_num: 1,
                interlocutor1: btr,
                interlocutor2: btr2,
                interlocutor3: btr3,
                interlocutor4: btr4,
                speaker1: thr1,
                speaker2: thr2,
                speaker3: thr3,
                speaker4: thr4,
              }).then(res => {
                console.log('res', res)
              })
            }

            if (btr||btr2||btr3||btr4) {
              this.$refs.PDF.cusRenderDomNoCodeImg()
            } else {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500)
            }
          }
          toast(res.msg)
        })
      }
    },
    addItem() {
      this.form.questionsList.push({
        "question": "",
        "answer": "",
        "orderNo": this.form.questionsList.length
      })
    },
    deleteItem(index) {
      this.form.questionsList.splice(index, 1)
    },
    getDocPhoto() {

      getDocPhoto({
        docId: this.$route.query.id,
        type: 1,
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length) {
            console.log(res.data)
          }
        } else {
          toast(res.msg)
        }
      })

    },
    getSign() {
      getSign({
        doc_photo_id: this.$route.query.id,
        type_num: 1
      }).then(res => {
        if (res.code === 200) {
          this.signList = res.data
          if (res.data.length) {
            this.jsonData.btr = this.form.btr = res.data[0].interlocutor1
            this.jsonData.btr2 = this.form.btr2 = res.data[0].interlocutor2
            this.jsonData.btr3 = this.form.btr3 = res.data[0].interlocutor3
            this.jsonData.btr4 = this.form.btr4 = res.data[0].interlocutor4

            this.jsonData.thr1 = this.form.thr1 = res.data[0].speaker1
            this.jsonData.thr2 = this.form.thr2 = res.data[0].speaker2
            this.jsonData.thr3 = this.form.thr3 = res.data[0].speaker3
            this.jsonData.thr4 = this.form.thr4 = res.data[0].speaker4
          }

        } else {
          toast(res.msg)
        }
      })
    },
    upImg() {
      // uploadLp({
      //   filePath: res.data.url,
      //   // path: res.path
      // }).then(res => {
      //   console.log('res', res)
      //   if (res.code === 0) {
      //
      //   }
      // })
    }
  },
  mounted() {
    this.init()
  },
};
</script>

<style scoped lang="scss">
.border {
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.bd_0, .bd_1 {
  border-top: none;
}
</style>
